package com.javaweb.annotation.validate;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import com.javaweb.annotation.validate.impl.CarNoCheck;
import com.javaweb.annotation.validate.impl.EmailCheck;
import com.javaweb.annotation.validate.impl.IdCardCheck;
import com.javaweb.annotation.validate.impl.IpCheck;
import com.javaweb.annotation.validate.impl.PhoneNoCheck;
import com.javaweb.annotation.validate.impl.UsccCodeCheck;
import com.javaweb.constant.CommonConstant;
import com.javaweb.enums.CommonCheckEnum;

import jakarta.validation.Constraint;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import jakarta.validation.Payload;

/**
 * 常用校验注解
 * @see CommonCheckEnum
 * @author tank2140896
 */
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy=CommonlyUsedClass.class)
public @interface CommonlyUsed {

	/**
	 * 校验类型
	 * @see CommonCheckEnum
	 * @return CommonCheckEnum 校验类型
	 */
	CommonCheckEnum type();
	
	/**
	 * 是否允许空
	 * <p>
	 * 允许空时将不做校验，但是一旦不为空，将进行校验；不允许空时将做校验
	 * @return boolean true：允许空；false：不允许空
	 */
	boolean allowEmpty() default false;
	
	/* ↓↓↓↓↓↓↓↓↓↓严格模式下必须有↓↓↓↓↓↓↓↓↓↓ */
	/**
	 * 校验信息
	 * <p>
	 * 这里为全局通用参数校验失败信息
	 * @return String 校验信息
	 */
	String message() default CommonConstant.CHECK_FAIL_MESSAGE;
	
	/**
	 * 组
	 * @return Class<?>[] 组
	 */
	Class<?>[] groups() default {};
	
	/**
	 * payload
	 * @return Class<? extends Payload>[] payload
	 */
	Class<? extends Payload>[] payload() default {};
	/* ↑↑↑↑↑↑↑↑↑↑严格模式下必须有↑↑↑↑↑↑↑↑↑↑ */
	
}

/**
 * 常用校验总处理类
 * @author tank2140896
 */
class CommonlyUsedClass implements ConstraintValidator<CommonlyUsed,Object> {
    
	/**
	 * 常用校验注解
	 */
	protected CommonlyUsed commonlyUsed;
	
	/**
	 * 初始化
	 */
	@Override
	public void initialize(CommonlyUsed commonlyUsed) {
		this.commonlyUsed = commonlyUsed;
	}

	/**
	 * 校验总方法
	 */
	@Override
	public boolean isValid(Object value,ConstraintValidatorContext context) {
		boolean allowEmpty = commonlyUsed.allowEmpty();
		if(allowEmpty){
			if(value==null){
				return true;
			}
		}
		if(value!=null) {
			String checkValue = value.toString().strip();
			CommonCheckEnum commonCheckEnum = commonlyUsed.type();
			//如果校验的情景过多，可以考虑将其存入map中去
			boolean pass = switch(commonCheckEnum) {
				case CAR_NO -> CarNoCheck.check(checkValue);
				case ID_CARD -> IdCardCheck.check(checkValue);
				case IP -> IpCheck.check(checkValue);
				case PHONE_NO -> PhoneNoCheck.check(checkValue);
				case USCC -> UsccCodeCheck.check(checkValue);
				case EMAIL -> EmailCheck.check(checkValue);
				default -> false;
			};
			return pass;
		}
		return false;
	}
	
}
